<?php

class NewMemberCreatedWorkflow extends RunTimeWorkflow
{
  
  const IN_MEMBER_ID = 'member_id';
  const IN_SUBJECT = 'subject';
  const IN_MESSAGE = 'message';
  
  /**
   * @var AbstractRecipientDeterminationSet
   */
  protected $recipients;

  public function __construct ($member, $options = array())
  {
    if ($member instanceof Member)
    {
      $container = new KeyValueWorkflowContainer();
      $container->setValue(self::IN_MEMBER_ID, $member->getId());
      $container->setValue(self::IN_SUBJECT, sprintf('Neues Mitglied "%s"', $member->getFullName()));
      $message = <<<EOD
%s hat %s zur Untergliederung "%s" hinzugefügt. 
EOD;
      $message = sprintf($message, $member->getCreator()->getDisplayName(), $member->getFullName(), $member->getOrganizationalUnit()->getName());
      $container->setValue(self::IN_MESSAGE, $message);
      
      $unit = $member->getOrganizationalUnit();
      $responsible_unit = $unit->getParentWithMemberResponsibility();
      
      $this->recipients = new DynamicRecipientDeterminationSet();
      $roles = $responsible_unit->getBoardMemberPropertyNames();
      foreach ($roles as $role)
      {
        $this->recipients->addRule(new OrganizationalUnitPropertyRecipientDeterminationRule($responsible_unit, $role));
      }
//      $this->recipients->addRule(new UserIdRecipientDeterminationRule(2));
      
      parent::__construct($container, $options);
    }
  }

  protected function configure ()
  {
    $this->getDesignTime()
      ->startNode()
      ->followedByParallelSplitWithForeachable('distributer', $this->recipients)
        ->followedBy(SimpleMessageWorkflowNode::createDesignTimeNode('iterator_message'))
          ->mapIn(self::IN_SUBJECT, SimpleMessageWorkflowNode::IN_SUBJECT)
          ->mapIn(self::IN_MESSAGE, SimpleMessageWorkflowNode::IN_MESSAGE)
          ->mapIn(self::IN_MEMBER_ID, ShowMemberWorkflowNodeAction::IN_MEMBER_ID)
          ->addAction(ShowMemberWorkflowNodeAction::createDesignTimeAction('show_member'))
          ->addAction(DeleteWorkflowNodeAction::createDesignTimeAction('delete'))
      ->endWithSynchronization()
      ->endNode();
  }
}